<?php

namespace Cs\Controller;

use Think\Controller;
use Think\Log;

class IndexController extends BaseControlle
{
    public function Index()
    {
        $assignmentid = I('get.assignmentid', 0, 'intval');
        $exam_topic = M('exam_topic');
        $exam_assignment = M('exam_assignment');
        $uid = I('session.studentid', 0, 'intval');
        $time = time();
        $exam_question_number = M('exam_question_number');
        $student_information = M('student_information');
        $DB_PREFIX = C('DB_PREFIX');
        //检测考试是否存在
        $is_exam_assignment = $exam_assignment->where(array('id' => $assignmentid))->find();
        if (!$is_exam_assignment) {
            $this->error('没有这项考试哦');
        }
        //检查用户权限
        $ret_student_information = $student_information->where(array('uid' => $uid))->find();
        if (!$ret_student_information) {
            $this->error('您无权参与考试');
        }
        //检查该学生是否有权参与这场考试
        //检查这场考试的面对的考试类型
        $ExamType = null;
        switch ($is_exam_assignment['unit']) {
            case 1:
                $exam_student = M('exam_student');
                $ret_exam_student = $exam_student->where(array('uid' => $uid, 'assignmentid' => $assignmentid))->find();
                if (!$ret_exam_student) {
                    $this->error('您不需要参与此次考试');
                }
                break;
            case 2:
                $exam_grade = M('exam_grade');
                $ret_exam_grade = $exam_grade->where(array('grade' => $ret_student_information['grade'], 'assignmentid' => $assignmentid))->find();
                if (!$ret_exam_grade) {
                    $this->error('您不需要参与此次考试');
                }
                break;
            case 3:
                $ExamType = null;
                break;
            case 4:
                $exam_class = M('exam_class');
                $ret_exam_class = $exam_class->where(array('class' => $ret_student_information['class'], 'assignmentid' => $assignmentid))->find();
                if (!$ret_exam_class) {
                    $this->error('您不需要参与此次考试');
                }
                break;
        }

        $ret_exam_question_number = $exam_question_number->where(array('exam_assignment_id' => $assignmentid))->order('sequence asc,id asc')->select();
        if (!$ret_exam_question_number) {
            $this->error('题库还没添加这场考试的相关信息，暂时无法考试');
        }


        $student_exam_result = M('student_exam_result');

        //终结超时没做的试卷
        $ret_exam_overtime = $student_exam_result->where(array('student_id' => $uid, 'exam_assignment_id' => $assignmentid, 'finish_time' => 0))->select();
        if ($ret_exam_overtime) {
            $overtime = $time + 30;
            foreach ($ret_exam_overtime as $key => $valuse) {
                if (($is_exam_assignment['duration'] + $valuse['start_time']) < $overtime) {
                    $student_exam_result->where(array('id' => $valuse['id']))->save(array('finish_time' => $is_exam_assignment['duration'] + $valuse['start_time']));
                }
            }
        }

        //检查该学生的该试卷做题上限是否到达
        $student_exam_result_where = array('student_id' => $uid, 'exam_assignment_id' => $assignmentid, 'finish_time' => array('neq', '0'));

        //是否限制做题次数is_frequency_restrict=1 则是有限制
        if ($is_exam_assignment['is_frequency_restrict']) {
            $count_student_exam_result = $student_exam_result->where($student_exam_result_where)->count();
            echo "您已做过{$count_student_exam_result}次该试卷,还可以做{$is_exam_assignment['max_frequency']}";
            if ($count_student_exam_result >= $is_exam_assignment['max_frequency']) {
                $this->error("您已做过{$count_student_exam_result}次该试卷，已经达到提交上限");
            }
        }

        //检查用户是否存在正在考试中的任务
        $ret_student_exam_result = $student_exam_result->where(array('student_id' => $uid, 'exam_assignment_id' => $assignmentid, 'finish_time' => 0))->find();
        $studentexamresult = $ret_student_exam_result['id'];
        $duration = $is_exam_assignment['duration'] + $ret_student_exam_result['start_time'] - $time;
        //如果没有存在于考试中的任务则，开始开始一个新的考试
        if (!$ret_student_exam_result) {
            $add_data = array(
                'exam_assignment_id' => $assignmentid,
                'unit' => $is_exam_assignment['unit'],
                'student_id' => $uid,
                'start_time' => $time,
                'examread_pattern' => $is_exam_assignment['grading_type']
            );
            $is_add_student_exam_result = $student_exam_result->data($add_data)->add();
            $studentexamresult = $is_add_student_exam_result;
            $duration = $is_exam_assignment['duration'] + $add_data['start_time'] - $time;
            if (!$is_add_student_exam_result) {
                $this->error('考试任务创建失败，请重试');
            }
        }

        //循环查询题库里面的题目
        $ret_exam = array();
        $inlay_topic = array();
        foreach ($ret_exam_question_number as $key => $value) {
            $ret_exam_topic = $exam_topic->where("{$DB_PREFIX}exam_topic.title_number='{$value['id']}' AND {$DB_PREFIX}job_library.last_job_library_id=0")
                ->join("__JOB_LIBRARY__ ON __JOB_LIBRARY__.id=__EXAM_TOPIC__.job_library_id", 'LEFT')
                ->order("{$DB_PREFIX}exam_topic.sequence ASC")
                ->field("{$DB_PREFIX}job_library.*,{$DB_PREFIX}exam_topic.id AS topicid,{$DB_PREFIX}exam_topic.sequence,{$DB_PREFIX}exam_topic.number")
                ->select();
            if ($ret_exam_topic) {
                $ret_exam[$key]['titleNumer'] = $value;
                $ret_exam[$key]['data'] = $ret_exam_topic;
            }
            $ret_exam_topic = $exam_topic->where("{$DB_PREFIX}exam_topic.title_number='{$value['id']}' AND {$DB_PREFIX}job_library.last_job_library_id!=0")
                ->join("__JOB_LIBRARY__ ON __JOB_LIBRARY__.id=__EXAM_TOPIC__.job_library_id", 'LEFT')
                ->order("{$DB_PREFIX}exam_topic.sequence ASC")
                ->field("{$DB_PREFIX}job_library.*,{$DB_PREFIX}exam_topic.id AS topicid,{$DB_PREFIX}exam_topic.sequence,{$DB_PREFIX}exam_topic.number")
                ->select();


            foreach ($ret_exam_topic as $k => $v) {
                $inlay_topic[$v['last_job_library_id']][] = $v;
            }
        }
        $this->assign('nav', 'Student_User');
        $this->assign('studentexamresult', $studentexamresult);
        $this->assign('website_title', '在线网校平台');
        $this->assign('title', $is_exam_assignment['examtitle']);
        $this->assign('assignmentid', $is_exam_assignment['id']);
        $this->assign('duration', $duration);
        $this->assign('ret_exam', $ret_exam);
        $this->assign('inlay_topic', $inlay_topic);
        $this->assign('examtitle', $is_exam_assignment['examtitle']);
        //$this->assign('job_library_list',$job_library_list);
        $this->theme('default')->display('index');
    }


    public function ExamResult()
    {
        ini_set('date.timezone', 'Asia/Shanghai');
        $answer = I('post.answer');
        $time = time();
        $uid = I('session.studentid', 0, 'intval');
        $assignmentid = I('post.assignmentid', 0, 'intval');
        $studentexamresult = I('post.studentexamresult', 0, 'intval');
        $exam_assignment = M('exam_assignment');
        $student_information = M('student_information');
        //print_r(I('post.'));


        //检查是否有这场考试
        $ret_exam_assignment = $exam_assignment->where(array('id' => $assignmentid))->find();
        if (!$ret_exam_assignment) {
            if (IS_AJAX) {
                $this->ajaxReturn(array('code' => 500, 'msg' => '该考试场次未找到'));
            } else {
                $this->error('该考试场次未找到');
            }
        }

        //检查用户权限
        $ret_student_information = $student_information->where(array('uid' => $uid))->find();
        if (!$ret_student_information) {
            if (IS_AJAX) {
                $this->ajaxReturn(array('code' => 500, 'msg' => '您无权参与考试'));

            } else {
                $this->error('您无权参与考试');
            }
        }


        //检查该学生是否有权参与这场考试
        //检查这场考试的面对的考试类型
        $ExamType = null;
        switch ($ret_exam_assignment['unit']) {
            case 1:
                $exam_student = M('exam_student');
                $ret_exam_student = $exam_student->where(array('uid' => $uid, 'assignmentid' => $assignmentid))->find();
                if (!$ret_exam_student) {
                    if (IS_AJAX) {
                        $this->ajaxReturn(array('code' => 500, 'msg' => '您不需要参与此次考试'));
                    } else {
                        $this->error('您不需要参与此次考试');
                    }
                }
                break;
            case 2:
                $exam_grade = M('exam_grade');
                $ret_exam_grade = $exam_grade->where(array('grade' => $ret_student_information['grade'], 'assignmentid' => $assignmentid))->find();
                if (!$ret_exam_grade) {
                    if (IS_AJAX) {
                        $this->ajaxReturn(array('code' => 500, 'msg' => '您不需要参与此次考试'));
                    } else {
                        $this->error('您不需要参与此次考试');
                    }
                }
                break;
            case 3:
                $ExamType = null;
                break;
            case 4:
                $exam_class = M('exam_class');
                $ret_exam_class = $exam_class->where(array('class' => $ret_student_information['class'], 'assignmentid' => $assignmentid))->find();
                if (!$ret_exam_class) {
                    if (IS_AJAX) {
                        $this->ajaxReturn(array('code' => 500, 'msg' => '您不需要参与此次考试'));
                    } else {
                        $this->error('您不需要参与此次考试');
                    }
                }
                break;
        }


        //检查该学生的该试卷做题上限是否到达
        $student_exam_result = M('student_exam_result');
        $student_exam_result_where = array('student_id' => $uid, 'exam_assignment_id' => $assignmentid, 'finish_time' => array('NEQ', 0));
        //是否限制做题次数is_frequency_restrict=1 则是有限制
        if ($ret_exam_assignment['is_frequency_restrict']) {
            $count_student_exam_result = $student_exam_result->where($student_exam_result_where)->count();
            if ($count_student_exam_result >= $ret_exam_assignment['max_frequency']) {
                if (IS_AJAX) {
                    $this->ajaxReturn(array('code' => 500, 'msg' => "您已做过{$count_student_exam_result}次该试卷，已经达到提交上限"));
                } else {
                    $this->error("您已做过{$count_student_exam_result}次该试卷，已经达到提交上限");
                }
            }
        }

        $ret_student_exam_result = $student_exam_result->where(array('student_id' => $uid, 'exam_assignment_id' => $assignmentid, 'finish_time' => 0))->find();
        //检查是否超过做题时间（+30秒，以防止系统时间不同步）
        if ($ret_student_exam_result['start_time'] + $ret_exam_assignment['duration'] < ($time + 30)) {
            if (IS_AJAX) {
                $this->ajaxReturn(array('code' => 500, 'msg' => '您已超过该场考试的最迟交卷时间'));
            } else {
                $this->error('您已超过该场考试的最迟交卷时间');
            }
        }

        //为了防止下面的循环处理出现意外，先将用户提交的答案，保存到数据库
        $update_db = array(
            'finish_time' => $time,
            'answer' => serialize($answer)
        );
        $return_student_exam_result = $student_exam_result->where(array('id' => $ret_student_exam_result['id']))->save($update_db);

        if (!$return_student_exam_result) {
            if (IS_AJAX) {
                $this->ajaxReturn(array('code' => 500, 'msg' => '提交失败，请重试'));
            } else {
                $this->error('提交失败，请重试');
            }
        }

        $exam_topic = M('exam_topic');
        //开始系统评分
        $score = 0;
        foreach ($answer as $key => $value) {
            $ret_exam_topic = $exam_topic->join("__JOB_LIBRARY__ ON __EXAM_TOPIC__.job_library_id=__JOB_LIBRARY__.id")
                ->where(array('exam_assignment_id' => $assignmentid, 'job_library_id' => intval($key)))
                ->find();
            $tmp_result = unserialize($ret_exam_topic['result']);
            $db_result = '';
            $result = '';

            if ($ret_exam_topic['type'] == 1) {
                foreach ($tmp_result as $k => $v) {
                    $db_result .= strtoupper($v);
                }

                if (is_array($value)) {
                    foreach ($value as $k => $v) {
                        $result .= strtoupper($v);
                    }
                } else {
                    $result = strtoupper($value);
                }
                if ($db_result == $result) {
                    $score += $ret_exam_topic['score'];
                }
            } elseif ($ret_exam_topic['type'] == 2) {
                foreach ($tmp_result as $k => $v) {
                    $db_result .= strtoupper($v);
                }

                if (is_array($value)) {
                    foreach ($value as $k => $v) {
                        $result .= strtoupper($v);
                    }
                } else {
                    $result = strtoupper($value);
                }

                if ($db_result == $result) {
                    $score += $ret_exam_topic['score'];
                }
            } elseif ($ret_exam_topic['type'] == 3) {
                $db_result = explode('|', $tmp_result);
                foreach ($db_result as $ret_key => $ret_value) {
                    if ($ret_value == $value) {
                        $score += $ret_exam_topic['score'];
                        break 2;
                    }
                }
            }/*elseif ($ret_exam_topic['type'] == 4){
                $db_result = explode('|',$tmp_result);
                foreach ($db_result as $ret_key=>$ret_value){
                    if ($ret_value == $value){
                        $score += $ret_exam_topic['score'];
                        break 2;
                    }
                }
            }*/

        }

        //根据阅卷模式分开处理
        //考完立即评分，即系统评分
        if ($ret_student_exam_result['examread_pattern'] == 0) {
            $ret = $student_exam_result->where(array('id' => $ret_student_exam_result['id']))->save(array('examread_pattern' => 0, 'is_examread' => 1, 'system_score' => $score, 'finally_score' => $score));
            if ($ret) {
                if (IS_AJAX) {
                    $this->ajaxReturn(array('code' => 200, 'msg' => '提交成功,您的得分' . $score . '（仅供参考，简答题未计算）'));
                } else {
                    $this->error('提交成功,您的得分' . $score . '（仅供参考，简答题未计算）');
                }
            } else {
                if (IS_AJAX) {
                    $this->ajaxReturn(array('code' => 200, 'msg' => '评分失败！答案已提交，请联系老师评分'));
                } else {
                    $this->error('评分失败！答案已提交，请联系老师评分');
                }
            }
        } else {//教师阅卷后评分
            $ret = $student_exam_result->where(array('id' => $ret_student_exam_result['id']))->save(array('system_score' => $score, 'examread_pattern' => 1));
            if ($ret) {
                if (IS_AJAX) {
                    $this->ajaxReturn(array('code' => 200, 'msg' => '提交成功，请等待老师阅卷'));
                } else {
                    $this->error('提交成功，请等待老师阅卷');
                }
            } else {
                if (IS_AJAX) {
                    $this->ajaxReturn(array('code' => 200, 'msg' => '系统尝试评分失败！答案已提交，请等待老师阅卷'));
                } else {
                    $this->error('系统尝试评分失败！答案已提交，请等待老师阅卷');
                }
            }
        }
    }

    //剩余时间查询，这个方法是个定时任务，客户端定时查询一次
    public function RemainingTestTime()
    {
        ini_set('date.timezone', 'Asia/Shanghai');
        $studentexamresultid = I('get.studentexamresultid', 0, 'intval');
        $student_exam_result = M('student_exam_result');
        $exam_assignment = M('exam_assignment');
        //数据缓存优化
        $ret_student_exam_result = $student_exam_result->where(array('id' => $studentexamresultid))->find();
        $ret_exam_assignment = $exam_assignment->where(array('id' => $ret_student_exam_result['exam_assignment_id']))->find();
        $s_count = 0;
        $time = time();
        $s = 0;
        $m = 0;
        if ($ret_student_exam_result) {
            //最迟交卷时间 = 开始考试时间 + 上考试时长
            //剩余时间 = 最迟交卷时间 - 现在时间
            $s_count = ($ret_student_exam_result['start_time'] + $ret_exam_assignment['duration']) - $time;
            $m = intval($s_count / 60);
            $s = $s_count % 60;
            $this->ajaxReturn(array('code' => 200, 'remainingtesttime' => array('m' => $m, 's' => $s)));
        } else {
            $this->ajaxReturn(array('code' => 500,));
        }
    }

}